package com.situ.manager.interceptor;

import com.situ.manager.pojo.Admin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//所有的请求首先经过拦截器
public class LoginInterceptor implements HandlerInterceptor {

    //previous
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户有没有登录
        //2.如果用户已经登录了，就方行，访问后端资源
        //3.如果没有登录，强制调转到登录界面
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            //用户之前没有登录,重定向到登录界面
            response.sendRedirect("/admin/toLogin");
            return false;
        }

        //登录成功，放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
